package bean.managed;

import entity.SalesInquiryEntity;
import bean.managed.util.JsfUtil;
import bean.managed.util.PaginationHelper;
import bean.session.SalesInquiryEntityFacade;

import entity.CustomerEntity;
import entity.PriceListEntity;
import entity.ProductQuantityPriceEntity;
import entity.SalesLeadEntity;
import entity.SystemUserEntity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.event.ActionEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import managedbean.AbstractBacking;
import org.primefaces.event.SelectEvent;
import type.CustomerType;

@ManagedBean(name = "salesInquiryEntityController")
@SessionScoped
public class SalesInquiryEntityController extends AbstractBacking implements Serializable {

    private SalesInquiryEntity current;
    private SalesInquiryEntity viewCurrent;
    private DataModel items = null;
    private DataModel searchItems = null;
    @EJB
    private bean.session.SalesInquiryEntityFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    private String attribute = "id";
    private String input;
    private ProductQuantityPriceEntity currentPQP;
    private ProductQuantityPriceEntity currentPQP2;
    private ProductQuantityPriceEntity currentPQP3;
    private ProductQuantityPriceEntity currentPQP4;
    private SalesLeadEntity selectedSalesLead;
    private CustomerEntity selectedCustomer;
    //@ManagedProperty(value = "#{salesLeadEntityController}")
    private SalesLeadEntityController salesLeadEntityController;
    private CustomerEntityController customerEntityController;
    private SalesQuotationEntityController salesQuotationEntityController;

    public SalesInquiryEntityController() {
    }

    public SalesInquiryEntity getCurrent() {
        return current;
    }

    public void setCurrent(SalesInquiryEntity current) {
        this.current = current;
    }

    public SalesInquiryEntityFacade getEjbFacade() {
        return ejbFacade;
    }

    public void setEjbFacade(SalesInquiryEntityFacade ejbFacade) {
        this.ejbFacade = ejbFacade;
    }

    public SalesLeadEntityController getSalesLeadEntityController() {
        return salesLeadEntityController;
    }

    public void setSalesLeadEntityController(SalesLeadEntityController salesLeadEntityController) {
        this.salesLeadEntityController = salesLeadEntityController;
    }

    public boolean checkSystemUser() {
        if (getCurrentUser() instanceof SystemUserEntity) {
            return true;
        }
        return false;
    }

    public boolean checkSalesLead() {
        if (getLoginSalesLead() instanceof SalesLeadEntity) {
            return true;
        }
        return false;
    }

    public boolean checkCustomer() {
        if (getLoginCustomer() instanceof CustomerEntity) {
            return true;
        }
        return false;
    }

    public ProductQuantityPriceEntity getSelectedPQP() {
        if (currentPQP == null) {
            currentPQP = new ProductQuantityPriceEntity();
            selectedItemIndex = -1;
        }
        return currentPQP;
    }

    public ProductQuantityPriceEntity getSelectedPQP2() {
        if (currentPQP2 == null) {
            currentPQP2 = new ProductQuantityPriceEntity();
            selectedItemIndex = -1;
        }
        return currentPQP2;
    }

    public ProductQuantityPriceEntity getSelectedPQP3() {
        if (currentPQP3 == null) {
            currentPQP3 = new ProductQuantityPriceEntity();
            selectedItemIndex = -1;
        }
        return currentPQP3;
    }

    public ProductQuantityPriceEntity getSelectedPQP4() {
        if (currentPQP4 == null) {
            currentPQP4 = new ProductQuantityPriceEntity();
            selectedItemIndex = -1;
        }
        return currentPQP4;
    }

    public SalesInquiryEntity getSelected() {
        if (current == null) {
            current = new SalesInquiryEntity();
            selectedItemIndex = -1;
        }
        return current;
    }

    public SalesInquiryEntityFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {

                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "/entities/salesInquiryEntity/List?faces-redirect=true";
    }

    public String prepareView() {
        current = (SalesInquiryEntity) getItems().getRowData();
        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View?faces-redirect=true";
    }

    public String viewAfterCreate() {
        viewCurrent = current;
        prepareCreate();
        return "ViewCreate?faces-redirect=true";
    }

    public void convertFromViewCreate(ActionEvent event) {
        current = viewCurrent;
        recreateModel();
    }

    public String prepareCreate() {
        current = new SalesInquiryEntity();
        //selectedItemIndex = -1;
        return "/entities/salesInquiryEntity/Create?faces-redirect=true";
    }

    public String prepareSearchForm() {

        return "/entities/salesInquiryEntity/Search?faces-redirect=true";
    }

    public String create() {
        try {
            ProductQuantityPriceEntity pqp;

            if (checkSystemUser()) {
                current.setSystemUser(getCurrentUser());
            } else if (checkSalesLead()) {
                current.setSalesLead(getLoginSalesLead());
            } else if (checkCustomer()) {
                current.setCustomer(getLoginCustomer());

            }

            currentPQP.setProduct(getFacade().getSalesInquiryProduct("Classic Nutri Bar (Nuts)"));
            current.getPqp().add(currentPQP);
            if (currentPQP.getQuantity() > 0) {
                pqp = currentPQP;
                //currentPQP.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP.setSalesInquiry(current);
            currentPQP2.setProduct(getFacade().getSalesInquiryProduct("Classic Nutri Bar (Fruits)"));
            current.getPqp().add(currentPQP2);
            if (currentPQP2.getQuantity() > 0) {
                pqp = currentPQP2;
                //currentPQP2.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP2.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP2.setSalesInquiry(current);
            currentPQP3.setProduct(getFacade().getSalesInquiryProduct("Premium Power Bar (Chocolate Nuts)"));
            current.getPqp().add(currentPQP3);
            if (currentPQP3.getQuantity() > 0) {
                pqp = currentPQP3;
                //currentPQP3.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP3.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP3.setSalesInquiry(current);
            currentPQP4.setProduct(getFacade().getSalesInquiryProduct("Premium Power Bar (Redcurrant Fruits)"));
            current.getPqp().add(currentPQP4);
            if (currentPQP4.getQuantity() > 0) {
                pqp = currentPQP4;
                //currentPQP4.setPricePerUnit(getPrice(pqp, current).get(0));
                currentPQP4.setPrice(getPrice(pqp, current).get(1));
            }
            currentPQP4.setSalesInquiry(current);

            current.setTotalPrice(currentPQP.getPrice() + currentPQP2.getPrice() + currentPQP3.getPrice() + currentPQP4.getPrice());

            current.created(getLoginPerson());
            currentPQP.created(getLoginPerson());
            currentPQP2.created(getLoginPerson());
            currentPQP3.created(getLoginPerson());
            currentPQP4.created(getLoginPerson());

            getFacade().create(current);

            if (current.getSalesLead() != null) {
                current.getSalesLead().getSalesInquiries().add(current);
                salesLeadEntityController.setCurrent(current.getSalesLead());
                salesLeadEntityController.update();
            }
            if (current.getCustomer() != null) {
                current.getCustomer().getSalesInquiries().add(current);
                customerEntityController.setCurrent(current.getCustomer());
                customerEntityController.update();
            }



            viewCurrent = null;
            currentPQP = null;
            currentPQP2 = null;
            currentPQP3 = null;
            currentPQP4 = null;
            recreateModel();
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesInquiryEntityCreated"));
            return viewAfterCreate();
        } catch (Exception e) {
            e.printStackTrace();
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareSearch() {
        searchItems = getSearchItems();
        return "/entities/salesInquiryEntity/SearchList?faces-redirect=true";
    }

    public DataModel getSearchItems() {
        //pagination = getPagination();
        if (getAttribute().equals("id")) {
            searchItems = ejbFacade.searchSalesInquiryById(getAttribute(), getInput());
        } else if (getAttribute().equals("Name")) {
            searchItems = ejbFacade.searchSalesInquiryByName(getAttribute(), getInput());
        } else if (getAttribute().equals("createdBy")) {
            searchItems = ejbFacade.searchSalesInquiryByCreatedBy(getInput());
        }
        items = searchItems;
        return searchItems;
    }

    public String prepareEdit() {
        current = (SalesInquiryEntity) getItems().getRowData();
        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit?faces-redirect=true";
    }

    public String update() {
        try {
            current.modified(getLoginPerson());
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesInquiryEntityUpdated"));
            return "View?faces-redirect=true";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (SalesInquiryEntity) getItems().getRowData();
        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreateModel();
        return "List?faces-redirect=true";
    }

    public String convert() {
        current = (SalesInquiryEntity) getItems().getRowData();
        //selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return prepareConvert();
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        //updateCurrentItem();
        //if (selectedItemIndex >= 0) {
        //    return "View?faces-redirect=true";
        //} else {
        // all items were removed - go back to list
        return "List?faces-redirect=true";
        //}
    }

    public void performDestroy() {
        try {
            current.modified(getLoginPerson());
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("SalesInquiryEntityDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    public DataModel getItems() {
        if (items == null) {
            if (getLoginPerson() instanceof SystemUserEntity) {
                items = getFacade().getAllSalesInquiry();
            } else if (getLoginPerson() instanceof SalesLeadEntity) {
                items = getFacade().getAllSalesInquiryForSalesLead(getLoginPerson().getId());
            } else if (getLoginPerson() instanceof CustomerEntity) {
                items = getFacade().getAllSalesInquiryForCustomer(getLoginPerson().getId());
            }

        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List?faces-redirect=true";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List?faces-redirect=true";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public ProductQuantityPriceEntity getCurrentPQP3() {
        return currentPQP3;
    }

    public void setCurrentPQP3(ProductQuantityPriceEntity currentPQP3) {
        this.currentPQP3 = currentPQP3;
    }

    public ProductQuantityPriceEntity getCurrentPQP4() {
        return currentPQP4;
    }

    public void setCurrentPQP4(ProductQuantityPriceEntity currentPQP4) {
        this.currentPQP4 = currentPQP4;
    }

    public SalesInquiryEntity getViewCurrent() {
        return viewCurrent;
    }

    public void setViewCurrent(SalesInquiryEntity viewCurrent) {
        this.viewCurrent = viewCurrent;
    }

    public CustomerEntityController getCustomerEntityController() {
        return customerEntityController;
    }

    public void setCustomerEntityController(CustomerEntityController customerEntityController) {
        this.customerEntityController = customerEntityController;
    }

    public SalesLeadEntity getSelectedSalesLead() {
        return selectedSalesLead;
    }

    public void setSelectedSalesLead(SalesLeadEntity selectedSalesLead) {
        this.selectedSalesLead = selectedSalesLead;
    }

    public CustomerEntity getSelectedCustomer() {
        return selectedCustomer;
    }

    public void setSelectedCustomer(CustomerEntity selectedCustomer) {
        this.selectedCustomer = selectedCustomer;
    }

    public SalesQuotationEntityController getSalesQuotationEntityController() {
        return salesQuotationEntityController;
    }

    public void setSalesQuotationEntityController(SalesQuotationEntityController salesQuotationEntityController) {
        this.salesQuotationEntityController = salesQuotationEntityController;
    }

    @FacesConverter(forClass = SalesInquiryEntity.class)
    public static class SalesInquiryEntityControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            SalesInquiryEntityController controller = (SalesInquiryEntityController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "salesInquiryEntityController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof SalesInquiryEntity) {
                SalesInquiryEntity o = (SalesInquiryEntity) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + SalesInquiryEntityController.class.getName());
            }
        }
    }

    public ArrayList<Double> getPrice(ProductQuantityPriceEntity pqp, SalesInquiryEntity inquiry) {
        System.out.println("gettingprice");
        PriceListEntity priceList;

        if (inquiry.getSalesLead() != null) {
            if (inquiry.getSalesLead().getCustomerType().equals(CustomerType.Wholesales)) {
                priceList = getTypePriceList(CustomerType.Wholesales, pqp);
            } else {
                priceList = getTypePriceList(CustomerType.Directsales, pqp);
            }
        } else {
            if (inquiry.getCustomer().getCustomerType().equals(CustomerType.Wholesales)) {
                priceList = getTypePriceList(CustomerType.Wholesales, pqp);
            } else {
                priceList = getTypePriceList(CustomerType.Directsales, pqp);
            }
        }
        return calculatePrice(pqp, priceList);
    }

    public PriceListEntity getTypePriceList(CustomerType type, ProductQuantityPriceEntity pqp) {
        System.out.println("gettingtype");
        PriceListEntity typePriceList = new PriceListEntity();
        ArrayList<PriceListEntity> priceList = getFacade().getPriceList();

        for (int i = 0; i < priceList.size(); i++) {
                if (priceList.get(i).getProduct().getId() == pqp.getProduct().getId() && priceList.get(i).getType().equals(type) && pqp.getQuantity() >= priceList.get(i).getTieredQuantity()) {
                    typePriceList = priceList.get(i);
                }
        }
        return typePriceList;
    }

    public ArrayList<Double> calculatePrice(ProductQuantityPriceEntity pqp, PriceListEntity priceList) {
        System.out.println("calculating price");
        ArrayList price = new ArrayList<Double>();
        price.add(priceList.getPrice());
        price.add(pqp.getQuantity() * priceList.getPrice());
        return price;
    }

    public boolean displayCustomerTab() {
        if (checkSystemUser() && getSelected().getSalesLead() == null) {
            return true;
        } else {
            return false;
        }
    }

    public boolean displaySalesLeadTab() {
        if (checkSystemUser() && getSelected().getCustomer() == null) {
            return true;
        } else {
            return false;
        }
    }

    public String salesLeadSelect(SelectEvent event) {
        current.setSalesLead(selectedSalesLead);
        System.out.println(current.getSalesLead().getId());
        return "Create?faces-redirect=true";
    }

    public String customerSelect(SelectEvent event) {
        current.setCustomer(selectedCustomer);
        return "Create?faces-redirect=true";
    }

    public String reset() {
        current.setSalesLead(null);
        current.setCustomer(null);
        currentPQP = null;
        currentPQP2 = null;
        currentPQP3 = null;
        currentPQP4 = null;
        return "Create?faces-redirect=true";
    }

    public String prepareConvert() {
        salesQuotationEntityController.setCurrent(null);
        ProductQuantityPriceEntity pqp = new ProductQuantityPriceEntity();
        ProductQuantityPriceEntity pqp2 = new ProductQuantityPriceEntity();
        ProductQuantityPriceEntity pqp3 = new ProductQuantityPriceEntity();
        ProductQuantityPriceEntity pqp4 = new ProductQuantityPriceEntity();

        ArrayList<ProductQuantityPriceEntity> pqplist = new ArrayList<ProductQuantityPriceEntity>(current.getPqp());
        for (int i = 0; i < pqplist.size(); i++) {
            if (pqplist.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Nuts)")) {
                pqp.setProduct(pqplist.get(i).getProduct());
                pqp.setQuantity(pqplist.get(i).getQuantity());
                pqp.setPrice(pqplist.get(i).getPrice());
                salesQuotationEntityController.setCurrentPQP(pqp);
            } else if (pqplist.get(i).getProduct().getProductName().equals("Classic Nutri Bar (Fruits)")) {
                pqp2.setProduct(pqplist.get(i).getProduct());
                pqp2.setQuantity(pqplist.get(i).getQuantity());
                pqp2.setPrice(pqplist.get(i).getPrice());
                salesQuotationEntityController.setCurrentPQP2(pqp2);
            } else if (pqplist.get(i).getProduct().getProductName().equals("Premium Power Bar (Chocolate Nuts)")) {
                pqp3.setProduct(pqplist.get(i).getProduct());
                pqp3.setQuantity(pqplist.get(i).getQuantity());
                pqp3.setPrice(pqplist.get(i).getPrice());
                salesQuotationEntityController.setCurrentPQP3(pqp3);
            } else if (pqplist.get(i).getProduct().getProductName().equals("Premium Power Bar (Redcurrant Fruits)")) {
                pqp4.setProduct(pqplist.get(i).getProduct());
                pqp4.setQuantity(pqplist.get(i).getQuantity());
                pqp4.setPrice(pqplist.get(i).getPrice());
                salesQuotationEntityController.setCurrentPQP4(pqp4);
            }
        }

        if (current.getSalesLead() != null && current.getCustomer() == null) {
            salesQuotationEntityController.getSelected().setSalesLead(current.getSalesLead());
        }
        if (current.getCustomer() != null) {
            salesQuotationEntityController.getSelected().setCustomer(current.getCustomer());
        }
        recreateModel();
        return "Edit";
    }
}
